package com.example.springbootmybatisredis.controller;


import com.alibaba.excel.EasyExcel;
import com.example.springbootmybatisredis.conf.RowWriteHandler;
import com.example.springbootmybatisredis.conf.UploadDataListener;
import com.example.springbootmybatisredis.entity.BankInfo;
import com.example.springbootmybatisredis.service.BankInfoService;
import com.sun.deploy.net.URLEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

import static com.alibaba.excel.EasyExcel.*;

/**
 * ClassName:beginController
 * Package:com.example.easyexcel
 * Description:
 * easyexcel excel 下载demo
 * @date:2021/6/4 14:28
 * @author:xy
 */


@RestController
@RequestMapping("excel")
public class ExcelController {

      @Autowired
      private BankInfoService bankService ;

    @PostMapping("/read")
     void readExcel(){
        read(new File("J:\\Xworkspace/demo.xlsx"), BankInfo.class,new UploadDataListener()).sheet().doRead();

    }


    @GetMapping("/write")
     void writeExcel(){

        List<BankInfo> bankInfos = bankService.fandAll();


      //   EasyExcel.write("D:\\demo666.xlsx", BankInfo.class).sheet("银行").doWrite(bankInfos);

        System.out.println("1121--------------------");
        write("D:\\\\demo666.xlsx",BankInfo.class).sheet("银行").registerWriteHandler(new RowWriteHandler()).doWrite(bankInfos);
    }


    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        List<BankInfo> bankInfos = bankService.fandAll();
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), BankInfo.class).sheet("模板").doWrite(bankInfos);
    }


    @PostMapping("upload")
    @ResponseBody
    public String upload(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), BankInfo.class, new UploadDataListener()).sheet().doRead();
        return "success";
    }
}
